<script setup>
import {Search} from "@element-plus/icons-vue";
import {ref, reactive, computed} from 'vue';
import {useRouter, useRoute} from 'vue-router';
import request from "@/utils/http.js";
import {ElMessage} from "element-plus";
import ImageClassifier from "@/components/base/imageClassifier.vue";
import { useUserStore } from "@/stores/user.js";

const formLableWidth = '140px'

const dialogRegister = ref(false)

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const activeIndex = computed(() => {
  const path = route.path;

  if (path.startsWith('/finance')) {
    return '/finance';
  }
  if (path.startsWith('/userCenter')) {
    return '/userCenter/home';
  }

  // 专家模块细分高亮
  if (path === '/expertHomePage') {
    return '/expertHomePage';
  }
  if (path.startsWith('/expert/questionPage')) {
    return '/expert/questionPage';
  }
  if (path.startsWith('/expert/newArticle')) {
    return '/expert/newArticle';
  }

  // 其他 /expert 路由（如 /expert/detail/:uid 等）默认归到专家首页
  if (path.startsWith('/expert')) {
    return '/expertHomePage';
  }

  return path;
});

const regRef = ref(null)

const regForm = reactive({
  regData:{
    role:'',
    uid: '',
    username: '',
    password: '',
    phone:'',
  }
})

const loading=ref(false)

const searchInput = ref('');  // 搜索输入框的值
const searchType = ref('1');  // 搜索类型，1为供应，2为采购

const handleRegister = () => {
  if (regRef.value) {
    regRef.value.validate((valid) => {
      if (valid) {
        request.post('/user/register', regForm.regData).then(res => {
          if (res.code === 200) {
            ElMessage.success("注册成功")
            dialogRegister.value = false  // 关闭对话框
          } else {
            ElMessage.error("注册失败,账号存在或网络错误,请重试！")
          }
        }).catch(error => {
          console.error(error)
          ElMessage.error("注册过程中发生错误，请稍后重试")
        });
      }
    });
  } else {
    ElMessage.error("表单验证失败，请检查输入")
  }
}

const goToLogin = () => {
  router.push('/login');
};

const searchGoods = () => {

  if (!searchInput.value) {
    ElMessage.warning('请输入搜索关键词');
    return
  }
  router.push({
    path:`/category/${searchInput.value}`,
    query:{
      date:new Date().getTime()
    }
  })


  // 根据searchType判断跳转到不同的页面
  // const targetPath = searchType.value === '1' ? '/supplyHall' : '/procurementHall';
  // router.push({
  //   path: targetPath,
  //   query: {
  //     keyword: searchInput.value,
  //     pageNum: 1,
  //     pageSize: 12
  //   }
  // });
};

// 监听输入框值变化
const changeMessage = (event) => {
  searchInput.value = event;
};

const goodsClass=ref('')

const openCustomerService = () => {
  window.open('http://localhost:8080/customer-service', '_blank')
}

</script>

<template>


  <div class="nav-wrapper">
    <div>

      <el-container style="height: 75px; background-color: white" direction="vertical">
        <el-header style="display: flex; justify-content: center; align-items: center;">



          <div class="logo-content" >
              <div style="display: flex">
                <div class="left">
                  <img src="../../assets/logo.png" style="width: 80px; height: 80px" alt="智农销平台">
                </div>
                <div style="display:inline-grid">
                  <img src="../../assets/ZhiNongXiao-green.png" style="height: 30px;padding-top: 20px;padding-left: 10px" alt="">
                  <img src="../../assets/web-address2.png" style="width: 150px;height:15px;padding-bottom: 10px;padding-left: 10px" alt="">
                </div>
              </div>
          </div>

          <div class="search-tag" style="flex: 1;
          display: flex;
          justify-content: center;
          margin-right: 180px"
               v-loading="loading"
               element-loading-text="正在识别...">
            <el-input 
              class="inputBar"
              v-model="searchInput"
              placeholder="请输入您要的货品"
              @input="changeMessage($event)"
              @keyup.enter="searchGoods"
            >
              <template #prefix>
                <el-select 
                  v-model="searchType"
                  class="gSelect" 
                  style="width: 100px;background-color: white" 
                  placeholder="供应"
                >
                  <el-option label="供应" value="1" />
                  <el-option label="采购" value="2" />
                </el-select>
              </template>

              <template #suffix>
                <image-classifier v-model:input="searchInput" v-model:loading="loading" style="margin-top: 10px;margin-right: 10px"></image-classifier>
                <el-button 
                  :icon="Search" 
                  @click="searchGoods" 
                  style="background-color: #39bf3e;color: white;font-size: 14px">搜索</el-button>

              </template>
            </el-input>
          </div>
<!--          </el-affix>-->
          <div class="reg-log" v-show="false">
            <el-button type="primary" round @click="dialogRegister = true">注册</el-button><br>
            <el-button type="primary" round @click="goToLogin">登录</el-button>
          </div>
<!--          <div class="search-tag" style="flex: 1; display: flex; justify-content: center;">-->
<!--            <el-input style="max-width: 600px" placeholder="请输入您要的货品"></el-input>-->
<!--          </div>-->
        </el-header>
      </el-container>

    </div>

    <div class="menu-content" v-cloak>
      <el-menu id="menu"
               mode="horizontal"
               active-text-color="#39bf3e"
               :default-active="route.path"
               router >
        <el-menu-item index="/homePage" class="item" >
          <span slot="title" >首页</span>
        </el-menu-item>
        <el-menu-item index="/procurementHall" class="item">
          <span slot="title">采购大厅</span>
        </el-menu-item>
        <el-menu-item index="/expertHomePage" class="item">
          <span>农技学堂</span>
        </el-menu-item>
        <el-menu-item index="/expert/questionPage" class="item">
          <span>专家问答</span>
        </el-menu-item>
        <el-menu-item v-if="userStore.isLogin && userStore.userInfo.role==='expert'" index="/expert/newArticle" class="item">
          <span>发布文章</span>
        </el-menu-item>
        <el-menu-item index="/finance/project" class="item">
          <span>融资申请</span>
        </el-menu-item>
        <el-menu-item index="/userCenter/home" class="item">
         <span>个人信息</span>
        </el-menu-item>
        <el-menu-item v-if="userStore.isLogin" index="/customer-service" class="item" @click="openCustomerService">
         <span>联系客服</span>
        </el-menu-item>
      </el-menu>
    </div>
  </div>


  <el-dialog v-model="dialogRegister" title="用户注册" width="30%">
    <el-form :model="regForm.regData" ref="regRef">
      <el-form-item label="账号用途:" :label-width="formLableWidth">
        <el-select v-model="regForm.regData.role">
          <el-option label="出售农产" value="user"/>
          <el-option label="采购农产" value="user"/>
          <el-option label="专家入驻" value="expert"/>
        </el-select>
      </el-form-item>
      <el-form-item label="账号" :label-width="formLableWidth">
        <el-input v-model="regForm.regData.uid" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="账户名" :label-width="formLableWidth">
        <el-input v-model="regForm.regData.username"/>
      </el-form-item>
      <el-form-item label="密码" :label-width="formLableWidth">
        <el-input v-model="regForm.regData.password" type="password"/>
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogRegister = false">取消</el-button>
        <el-button type="primary" @click="handleRegister">注册</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="less">

.el-menu-item:hover{
  background: #39bf3e !important;
  color: #fff !important;
  text-align: center;
}

.inputBar{
  max-width: 600px;
  height: 45px;
  font-size: 12px;
  :deep(.el-input__wrapper) {
    border-radius:10px;
    box-shadow: 0 0 0 0.45mm #39bf3e inset;
}
}

.gSelect{
  :deep(.el-select__wrapper) {
    box-shadow:0 0 0 0;
  }
}

.el-menu-item{
  font-size: 16px;
  font-weight: bold;
  margin: 0 20px ;
}

.menu-content{
  background-color: #fff;
}

.el-menu{
  background-color: #fff;
  display: flex;
  justify-content: center;
  margin: 0 auto;
  height: 50px;
}

.nav-wrapper{
  background-color: #fff;
}

</style>
